<?php
/**
 * @author spenceryg
 * @date 2022/1/30
 * @time 9:48 上午
 * @focus love & life
 */


namespace app\admin\middleware;


use app\admin\controller\sys\business\AdminUserBusiness;
use think\facade\Session;

class Auth
{
    public function handle($request, \Closure $next){
//        session(config('admin.admin_session'),null);
        $pathInfo = strtolower($request->pathinfo());
        if(!$pathInfo){
            $url = '/admin/sys.index/index';
        }else{
            if(strpos($pathInfo, '/')===false){
                $url = '/admin/'.$pathInfo.'/index';
            }else{
                $url = '/admin/' . $pathInfo;
            }
        }
        $url = strtolower($url);
        $url = str_replace('.' . config('view.view_suffix'), '', $url);


        $is_login_page = strstr($pathInfo, 'sys.login');
        $admin_user = session(config('admin.admin_session'));
        $is_not_login = empty($admin_user);
        if($is_not_login && !$is_login_page){
             return redirect(url('sys.login/index'));
        }
        if(!$is_not_login && $is_login_page){
            return  redirect(url('sys.index/index'));
        }


        if(!$is_login_page){
            $request->admin_user_id = $admin_user['id'];
            $request->menu = session(config('admin.node_session'));
            $request->access_arr = session(config('admin.access_session'));
//            return error('', AdminUserBusiness::getAccess($request->admin_user_id));
            if($request->access_arr  != '*'){
                if(!in_array($url, $request->access_arr) && !$admin_user['is_super']){
                    //todo 2种情况单独处理
                    if($request->isPost()){
                        return error('没有权限',[$request->menu, $request->access_arr,$request->admin_user_id]);
                    }else{
                        return error('没有权限',[$request->menu, $request->access_arr,$request->admin_user_id]);
                    }
                }
            }

        }
//        return error('没有权限',[$request->menu, $request->access_arr,$request->admin_user_id]);

        return $next($request);
    }
}
